/*
 *    Copyright 2022 The DSMS Authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.dsms.modules.task.service.impl;

import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dsms.common.constant.RemoteResponseStatusEnum;
import com.dsms.common.constant.TaskStatusEnum;
import com.dsms.common.remotecall.model.FailedDetail;
import com.dsms.common.remotecall.model.FinishedDetail;
import com.dsms.common.remotecall.model.RemoteResponse;
import com.dsms.common.taskmanager.TaskException;
import com.dsms.common.taskmanager.model.Step;
import com.dsms.common.taskmanager.service.IStepService;
import com.dsms.dfsbroker.common.api.CommonApi;
import com.dsms.modules.task.mapper.StepMapper;
import com.dsms.modules.util.RemoteCallUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;

/**
 * Implementation of step operation service
 */
@Service
public class StepServiceImpl extends ServiceImpl<StepMapper, Step> implements IStepService {

    private static final int RETRY_TIME = 3;

    @Autowired
    private CommonApi commonApi;

    @Override
    public Step getStepResponse(Step step, RemoteResponse executeResponse) throws Throwable {
        //get response of step request
        RemoteResponse stepResult = commonApi.getRequestResult(RemoteCallUtil.generateRemoteRequest(), RETRY_TIME, executeResponse.getId());

        //analytic response result
        if (Objects.equals(stepResult.getState(), RemoteResponseStatusEnum.SUCCESS.getMessage())) {
            step.setStepStatus(TaskStatusEnum.FINISH.getStatus());
        } else if (Objects.equals(stepResult.getState(), RemoteResponseStatusEnum.FAILED.getMessage())) {
            List<FailedDetail> failed = stepResult.getFailed();
            String failedMessage = StringUtils.hasText(failed.get(0).getOutb()) ? failed.get(0).getOutb() : failed.get(0).getOuts();
            step.setStepErrorMessage(failedMessage);
            step.setStepStatus(TaskStatusEnum.FAIL.getStatus());
        } else if (ObjectUtils.isEmpty(stepResult.getState())) {
            step.setStepErrorMessage("unknown request state,response:" + JSON.toJSONString(stepResult));
        }
        return step;
    }

    @Override
    public Step getStepResponse(Step step, RemoteResponse executeResponse, List<String> successMsg, String errMsg) throws Throwable {
        //get response of step request
        RemoteResponse resultResponse = commonApi.getRequestResult(RemoteCallUtil.generateRemoteRequest(), RETRY_TIME, executeResponse.getId());

        //analytic response result
        if (Objects.equals(resultResponse.getState(), RemoteResponseStatusEnum.SUCCESS.getMessage())) {
            List<FinishedDetail> finished = resultResponse.getFinished();
            String finishedMessage = StringUtils.hasText(finished.get(0).getOutb()) ? finished.get(0).getOutb() : finished.get(0).getOuts();
            boolean isSuccess = false;
            for (String msg : successMsg) {
                if (Objects.equals(msg, finishedMessage) || finishedMessage.contains(msg)) {
                    isSuccess = true;
                    break;
                }
            }
            if (isSuccess) {
                step.setStepStatus(TaskStatusEnum.FINISH.getStatus());
                //some step needs success result
                step.setSuccessMessage(finishedMessage);
            } else {
                step.setStepErrorMessage(finishedMessage);
                step.setStepStatus(TaskStatusEnum.FAIL.getStatus());
                throw new TaskException(errMsg + StrPool.COMMA + finishedMessage);
            }
        } else if (Objects.equals(resultResponse.getState(), RemoteResponseStatusEnum.FAILED.getMessage())) {
            List<FailedDetail> failed = resultResponse.getFailed();
            String failedMessage = StringUtils.hasText(failed.get(0).getOutb()) ? failed.get(0).getOutb() : failed.get(0).getOuts();
            step.setStepErrorMessage(failedMessage);
            step.setStepStatus(TaskStatusEnum.FAIL.getStatus());
            throw new TaskException(errMsg + StrPool.COMMA + failedMessage);
        } else if (ObjectUtils.isEmpty(resultResponse.getState())) {
            throw new TaskException("unknown request state,response:" + JSON.toJSONString(resultResponse));
        }
        return step;
    }
}
